<?php
/**
 * Created by PhpStorm.
 * User: CYJiao
 * Date: 6/22/15
 * Time: 09:15
 */

class CommunityController extends Controller
{

    /**
     * Method returning filters array.
     */
    public function filters()
    {
        return array(
            'accessControl',//Performs access control for CRUD operations
        );
    }

    /**
     * Defines User Access Level.
     */
    public function accessRules()
    {
        return array(
            array('allow',
                'actions'=>array(),//Actions allowed
                'roles'=>array('@'),//Roles allowed to perform actions
            ),
            array('deny',
                'actions'=>array(),//Actions not allowed
                'roles'=>array('*'),//Roles not allowed to perform actions
            ),
        );
    }

    /**
     * Declares class-based actions.
     */
    public function actions(){
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'height'=>37,
                'minLength'=>4,
                'maxLength'=>6,
                'backColor'=>0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page'=>array(
                'class'=>'CViewAction',
            ),
        );
    }

    /******************************************************************************************
     * Following functions are related to News
     ******************************************************************************************/

    /**
     * Getting News Content Index
     */
    public function actionContentdetail(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
           
           $this->renderPartial('contentdetail');
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionContent(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
           $this->render('content',array('pk_outpatient_id'=>Yii::app()->session['id']));
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionadd(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
           $this->render('add');
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionlist(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
           $this->render('list');
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionSave(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $article_id = guid();
            $topics_arr = array();
            $count_post = count($_POST['data']);
            $title = $_POST['data'][0]['value'];
            $topic_result = array();
            for ($i=1; $i < $count_post - 1 ; $i++) { 
                $topics_arr[] = $_POST['data'][$i]['value'];
            }
            $content = $_POST['data'][$count_post - 1]['value'];

            $topic = array(array('topicId'=>1,'topicName'=>'内科'),array('topicId'=>2,'topicName'=>'外科'),array('topicId'=>3,'topicName'=>'妇科'),array('topicId'=>4,'topicName'=>'儿科'),array('topicId'=>5,'topicName'=>'中医保健'),array('topicId'=>6,'topicName'=>'营养美食'),array('topicId'=>7,'topicName'=>'其他'),array('topicId'=>8,'topicName'=>'病友圈'),array('topicId'=>9,'topicName'=>'求关心'),array('topicId'=>10,'topicName'=>'求帮助'));
            
            foreach ($topics_arr as $key => $topics) {
               $topic_result[] = json_encode($topic[$topics-1]);
            }

            $doctorInfo = TblDoctorInformation::model()->findByAttributes(array('pk_fk_doctor_id'=>Yii::app()->session['id']));

        
            $pk_doctor_id = Yii::app()->session['id'];//Yii::app()->session['id'];
            $conn = new mongoClient($GLOBALS['mongodb']['connectionString']);
            $db = $conn->o2omongo;
            $collection_doctor_relations = $db->selectCollection('cf_'.$pk_doctor_id.'_doctor_relations');

            //获取第一张图片生成缩略图
            $pre = '{<img .*src="(\S*)"}';
            preg_match_all($pre, $content, $matches);

            if(isset($matches[1][0])){
                $little_img = $matches[1][0];

                if($_SERVER['REMOTE_ADDR'] == '127.0.0.1'){
                    $little_img = 'http://pic.o2omedical.com/article/150731/4f96ab302d31cb3c21057e9030e639d5.png';
                }else{
                    $little_img = str_replace('http://pic.o2omedical.com/', '/data/wwwroot/pic/', $little_img);
                }

                $little_img = file_upload($little_img,$pk_doctor_id);//curl 返回的json
                if(isset($little_img['fileId'])){
                    $little_img = array(json_encode(array('pictureId'=>$little_img['fileId'],'pictureUrl'=>$little_img['fileUrl'],'pictureSuffix'=>$little_img['fileSuffix'])));
                }else{
                    $little_img = array();
                }
                
            }else{
                $little_img = array();
            }
           

            $doctor_relations = $collection_doctor_relations->find(array());//获取医生关系
            $rows = array();
            $user_relation_ids = array();
            $doctor_relation_ids = array();
            while ( $doctor_relations->hasNext()) {
                $rows = $doctor_relations->getNext();
                if($rows['user_id']){
                    $user_relation_ids[] = $rows['user_id'];//关系病人
                }elseif($rows['doctor_id']){
                    $doctor_relation_ids[] = $rows['doctor_id'];//关系医生
                }

            }

            $doctor_relation_ids[] = $pk_doctor_id;//把自己添加到关系医生数组

            $all_relations = array_merge($user_relation_ids,$doctor_relation_ids);

            if(isset($doctorInfo['doctor_file_suffix'])){
                $source_portrait = array('pictureSuffix'=>$doctorInfo['doctor_file_suffix'],'pictureUrl'=>$doctorInfo['doctor_file_url'],'pictureId'=>$doctorInfo['doctor_file_id']);
                $source_portrait = json_encode($source_portrait);
            }else{
                 $source_portrait = '';
            }
            
            
            //往文章表插入文章数据
            $db->selectCollection('cf_articles')->insert(array(
            'topics' => $topic_result,
            'title' => $title,
            'content' => $content,
            'article_id' => $article_id,
            'source_id' => new MongoInt64($pk_doctor_id),
            'source_portrait' => $source_portrait,
            'source_name' => Yii::app()->session['true_name'],
            'pictures' => $little_img,//array(0=>array())数组json化
            'share_count' => new MongoInt32(0),
            'forward_count' => new MongoInt32(0),
            'like_count' => new MongoInt32(0),
            'discuss_count' => new MongoInt32(0),
            'browse_count' => new MongoInt32(0),
            'article_status' => new MongoInt32(4),
            'readable_list' => $all_relations,
            'label' => new MongoInt32(0),
            'forward_user_id' => new MongoInt32(0),
            'forward_user_name' => '',
            'share_url' =>'',
            'forward_comment' => '',
            'create_time' => new MongoDate(time()),
            'update_time' => new MongoDate(time()),
            'delete_time' => new MongoDate(0)

            ));//文章表

            $db->selectCollection('cf_'.$pk_doctor_id.'_doctor_personal_dynamics')->insert(array(
            'personal_dynamic_id' => guid(),
            'article_id' => $article_id,
            'sharable' => new MongoInt32(1),
            'create_time' => new MongoDate(time()),
            'update_time' => new MongoDate(time()),
            

            ));//个人空间动态表

            foreach ($user_relation_ids as $key => $user_relation_id) {
                $db->selectCollection('cf_'.$user_relation_id.'_user_dynamics')->insert(array(
                'dynamic_id' => guid(),
                'article_id' => $article_id,
                'create_time' => new MongoDate(time()),
                'update_time' => new MongoDate(time()),
                'like_type' => new MongoInt32(2),
                'blocked' => new MongoInt32(1),
                ));//关系病人动态表
            }

            foreach ($doctor_relation_ids as $key => $doctor_relation_id) {
                $db->selectCollection('cf_'.$doctor_relation_id.'_doctor_dynamics')->insert(array(
                'dynamic_id' => guid(),
                'article_id' => $article_id,
                'create_time' => new MongoDate(time()),
                 'update_time' => new MongoDate(time()),
                'like_type' => new MongoInt32(2),
                'blocked' => new MongoInt32(1),

                ));//关系医生动态表
            }

            foreach ($topics_arr as $key => $topics) {
                $db->selectCollection('cf_'.$topics.'_category')->insert(array(
                'category_id' => guid(),
                'article_id' => $article_id,
                'create_time' => new MongoDate(time()),
                'update_time' => new MongoDate(time())
                ));//分类表
            }

            // $log = new Log600100(); //Create new empty record
            // $log->action = 'save_article';//Saving the action type
            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
            // $log->target = $article_id;//针对对象
            // $log->save(false);//Saving the entire record with validation

            echo json_encode(array('article_id'=>$article_id));
            exit;




            
           //$this->render('add');
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionListarticle(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $pk_doctor_id = Yii::app()->session['id'];//Yii::app()->session['id'];
            $conn = new mongoClient($GLOBALS['mongodb']['connectionString']);
            $db = $conn->o2omongo;
            $collection_doctor_articles = $db->selectCollection('cf_articles');

            // $collection_doctor_articles->remove(array('source_name' => '13828474888'), array("justOne" => true));
            // exit;

            $page_rows = empty($_POST['rows']) ? 20 : (int)$_POST['rows'];
            $offet = max(0,(int)($_POST['page'] - 1) * $page_rows);
            $condition['source_id'] = new MongoInt64($pk_doctor_id);
            $condition['article_status'] = array('$ne'=>3);
            if(isset($_POST['title'])) $condition['title'] = new MongoRegex("/.*".$_POST['title'].".*/i");
            $cursor = $collection_doctor_articles->find($condition)->sort(array("update_time" => -1))->limit($page_rows)->skip($offet);
            $result = array();
            $rows = array();
            $i = 0;
            while ($cursor->hasNext()) {
                $rows[$i] = $cursor->getNext();
                if(is_object($rows[$i]['create_time'])){
                    $rows[$i]['create_time'] = date('Y-m-d H:s:i',$rows[$i]['create_time']->sec);    
                }
                $i++;
            }

            // $log = new Log600100(); //Create new empty record
            // $log->action = 'list_article';//Saving the action type
            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
            // $log->target = '';//针对对象
            // $log->save(false);//Saving the entire record with validation



           
            $result['total'] = $collection_doctor_articles->find($condition)->count();
            $result['rows'] = $rows;
            echo json_encode($result);
            
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionFind(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $pk_doctor_id = Yii::app()->session['id'];//Yii::app()->session['id'];
            $conn = new mongoClient($GLOBALS['mongodb']['connectionString']);
            $db = $conn->o2omongo;
            $collection_doctor_articles = $db->selectCollection('cf_articles');

            $article_id = $_GET['article_id'];

            $condition['article_id'] = $article_id;

            $cursor = $collection_doctor_articles->find($condition);
            $result = array();
            $rows = array();
            while ($cursor->hasNext()) {
                $rows = $cursor->getNext();
            }
            $type = '';
            if(isset($_GET['from'])){
                $type = true;
            }

            // $log = new Log600100(); //Create new empty record
            // $log->action = 'find_article';//Saving the action type
            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
            // $log->target = $article_id;//针对对象
            // $log->save(false);//Saving the entire record with validation

            $this->render('contentdetail',array('rows'=>$rows,'type'=>$type)); 
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionUpdate(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $pk_doctor_id = Yii::app()->session['id'];//Yii::app()->session['id'];
            $conn = new mongoClient($GLOBALS['mongodb']['connectionString']);
            $db = $conn->o2omongo;
            $collection_doctor_articles = $db->selectCollection('cf_articles');

            

            if(isset($_POST['data'])){

                $topics_arr = array();
                $count_post = count($_POST['data']);
                $title = $_POST['data'][0]['value'];
                $article_id = $_POST['data'][1]['value'];
                $topic_result = array();
                for ($i=2; $i <= $count_post - 2 ; $i++) { 
                    $topics_arr[] = $_POST['data'][$i]['value'];
                }
                $content = $_POST['data'][$count_post - 1]['value'];

                //获取话题
                $topic = array(array('topicId'=>1,'topicName'=>'内科'),array('topicId'=>2,'topicName'=>'外科'),array('topicId'=>3,'topicName'=>'妇科'),array('topicId'=>4,'topicName'=>'儿科'),array('topicId'=>5,'topicName'=>'中医保健'),array('topicId'=>6,'topicName'=>'营养美食'),array('topicId'=>7,'topicName'=>'其他'),array('topicId'=>8,'topicName'=>'病友圈'),array('topicId'=>9,'topicName'=>'求关心'),array('topicId'=>10,'topicName'=>'求帮助'));
                $topic_result = array();
                foreach ($topics_arr as $key => $topics) {
                    $topic_result[] = json_encode($topic[$topics-1]);
                }


                //获取第一张图片生成缩略图
                $pre = '{<img .*src="(\S*)"}';
                preg_match_all($pre, $content, $matches);
                if(isset($matches[1][0])){
                    $little_img = $matches[1][0];
                    if($_SERVER['REMOTE_ADDR'] == '127.0.0.1'){
                        $little_img = 'http://pic.o2omedical.com/article/150731/4f96ab302d31cb3c21057e9030e639d5.png';
                    }else{
                        $little_img = str_replace('http://pic.o2omedical.com/', '/data/wwwroot/pic/', $little_img);
                    }

                    $little_img = file_upload($little_img,$pk_doctor_id);//curl 返回的json
                    if($little_img['fileId'] == ''){$little_img = array();}
                    else{$little_img = array(json_encode(array('pictureId'=>$little_img['fileId'],'pictureUrl'=>$little_img['fileUrl'],'pictureSuffix'=>$little_img['fileSuffix'])));}
                    
                }else{
                    $little_img = array();
                }
                

                $condition['article_id'] = $article_id;
                $cursor = $collection_doctor_articles->update(
                    $condition,
                    array('$set'=>array('title' => $title,
                          'topics' => $topic_result,
                          'content' => $content,
                          'pictures' => $little_img)));

                echo json_encode(array('article_id'=>$article_id));
                exit;
            }

            $article_id = $_GET['article_id'];
            $condition['article_id'] = $article_id;
            $cursor = $collection_doctor_articles->find($condition);
            $result = array();
            $rows = array();
            while ($cursor->hasNext()) {
                $rows = $cursor->getNext();
            }

            // $log = new Log600100(); //Create new empty record
            // $log->action = 'update_article';//Saving the action type
            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
            // $log->target = $article_id;//针对对象
            // $log->save(false);//Saving the entire record with validation

            $this->render('update',array('rows'=>$rows)); 
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionDel(){
         if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $pk_doctor_id = Yii::app()->session['id'];//Yii::app()->session['id'];
            $conn = new mongoClient($GLOBALS['mongodb']['connectionString']);
            $db = $conn->o2omongo;
            $collection_doctor_articles = $db->selectCollection('cf_articles');

            $article_id = $_GET['article_id'];

            $condition['article_id'] = $article_id;

            $cursor = $collection_doctor_articles->update($condition,array('$set'=>array('article_status' => new MongoInt32(3))));
            if($cursor) echo 'success';

            // $log = new Log600100(); //Create new empty record
            // $log->action = 'del_article';//Saving the action type
            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
            // $log->target = $article_id;//针对对象
            // $log->save(false);//Saving the entire record with validation
           
            exit;
            
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionUploadfile(){

        if($_SERVER['REMOTE_ADDR'] == '::1'){
            $path = BASE_DIR.'/data/';
            $url = Yii::app()->request->hostInfo.Yii::app()->request->baseUrl.'/data/';

        }else{
            $path = '/data/wwwroot/pic/article/';
            $url = 'http://pic.o2omedical.com/article/';
        }
        
        $image = CUploadedFile::getInstanceByName('imgFile');

        $ymd = date('ymd');
        $md5 = md5(time().rand(1, 10000));
        $name = $md5.'.'.$image->getExtensionName();
        $extensions_name = $image->getExtensionName();

        if(!is_dir($path.'/'.$ymd)){
            mkdir($path.'/'.$ymd);
        }
        $fileName = $name;
        $image->saveAs($path.'/'.$ymd.'/'.$fileName);
        

        makeThumbnail($path.'/'.$ymd.'/'.$fileName,$path.'/'.$ymd.'/'.$md5.'_360_auto.'.$extensions_name,360,360,true);//生成缩略图

        unlink($path.'/'.$ymd.'/'.$fileName);

        $url = $url.$ymd.'/'.$md5.'_360_auto.'.$extensions_name;

        
        $result = array('error'=>0,'url'=>$url);
        sleep(1);
        echo json_encode($result);
        // $log = new Log600100(); //Create new empty record
        // $log->action = 'upload_pic';//Saving the action type
        // $log->create_time = new CDbExpression('NOW()');//Saving date and time
        // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
        // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
        // $log->target = $url;//针对对象
        // $log->save(false);//Saving the entire record with validation
        // exit;

        //{"error":0,"url":"\/project\/css\/plugins\/editer\/image\/20150730\/20150730062858_89530.jpg"}
 
        //$this->redirect(array('index','dir'=>$this->currentDir));
    }

}
